<template>
  <div class="dashboard-container">
    <div class="app-container">
      <head-tool>
        <div class="btns" slot="after">
          <el-button
            type="primary"
            size="small"
            @click="$router.push({ path: '/import', query: { type: 'emp' } })"
          >
            导入
            <i class="el-icon-folder-add"> </i>
          </el-button>
          <el-button type="success" size="small" @click="exportExcel">
            导出
            <i class="el-icon-edit-outline"></i>
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="showDialog = true"
            v-if="checkPoint('POINT-ROLE-ADD')"
          >
            新增员工
          </el-button>
        </div>
      </head-tool>
      <el-card>
        <el-table :data="list">
          <el-table-column label="序号" type="index" align="center">
          </el-table-column>
          <el-table-column label="姓名" prop="username" align="center">
          </el-table-column>
          <el-table-column label="头像" prop="staffPhoto" align="center">
            <template slot-scope="{ row }">
              <img
                v-imgerror="defaultImg"
                :src="row.staffPhoto"
                alt=""
                style="width: 50px"
                @click="showQrCode(row.staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" align="center" sortable>
          </el-table-column>
          <el-table-column
            label="工号"
            prop="workNumber"
            align="center"
            sortable
          >
          </el-table-column>
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            align="center"
          >
            <template slot-scope="{ row }">
              {{ row.formOfEmployment | formatHireType }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" align="center">
          </el-table-column>
          <el-table-column
            label="入职时间"
            prop="timeOfEntry"
            align="center"
            sortable
          >
          </el-table-column>
          <el-table-column
            label="转正时间"
            prop="correctionTime"
            align="center"
            sortable
          >
          </el-table-column>
          <el-table-column label="状态" prop="enableState" align="center">
            <template slot-scope="{ row }">
              <el-switch
                v-model="row.enableState"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="160px"
            align="center"
          >
            <template
              slot-scope="{ row }"
              style="display: flex; justify-content: space-between"
            >
              <el-link
                type="primary"
                @click="
                  $router.push({
                    path: '/employees/detail',
                    query: { id: row.id },
                  })
                "
                >查看</el-link
              >
              <el-link type="primary">转正</el-link>
              <el-link type="primary">调岗</el-link>
              <el-link type="primary">离职</el-link>
              <el-link type="primary" @click="showRole(row.id)">角色</el-link>
              <el-link type="primary" @click="delEmp(row.id)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="pageInfo.page"
          :page-size="pageInfo.size"
          layout="total, prev, pager, next"
          :total="pageInfo.total"
          @current-change="pageChange"
        />
      </el-card>
      <add-emp :show-dialog.sync="showDialog" />
      <el-dialog :visible.sync="showCodeDialog" title="二维码">
        <!-- 二维码 -->
        <el-row type="flex" justify="center">
          <canvas ref="canvas"></canvas>
        </el-row>
      </el-dialog>
      <role-setting
        ref="roleset"
        :showRoleDialog.sync="showRoleDialog"
        :userId="currentId"
      ></role-setting>
    </div>
  </div>
</template>

<script>
import { getEmpLists, delEmp } from "@/api/employees";
import constant from "@/api/constant/employees";
import AddEmp from "./components/add-emp.vue";
import RoleSetting from "./components/role-setting.vue";
// 导入二维码插件
import qrcode from "qrcode";
export default {
  components: { AddEmp, RoleSetting },
  name: "employees",
  data() {
    return {
      showDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      currentId: "",
      pageInfo: {
        page: 1,
        size: 5,
        total: 0,
      },
      defaultImg: require("@/assets/common/head.jpg"),
      list: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 二维码的点击显示和隐藏
    showQrCode(url) {
      if (url) {
        this.showCodeDialog = true;

        this.$nextTick(() => {
          qrcode.toCanvas(this.$refs.canvas, url);
        });
      } else {
        this.$message.error("该用户没有头像!");
      }
    },
    async showRole(id) {
      this.currentId = id;
      this.showRoleDialog = true;
      await this.$refs.roleset.getUserInfo(id);
    },
    async getList() {
      let res = await getEmpLists(this.pageInfo);
      // console.log(res);
      this.pageInfo.total = res.data.total;
      this.list = res.data.rows;
      this.list.forEach((item) => {
        item.enableState = item.enableState == 1 ? true : false;
      });
      // console.log(this.list);
    },
    pageChange(page) {
      this.pageInfo.page = page;
      this.getList();
    },
    async delEmp(id) {
      try {
        await this.$confirm("确定要删除吗?");
        // let res = await delEmp(id);
        await delEmp(id);
        // console.log(res);
        this.getList();
        if (this.list.length == 1 && this.pageInfo.page != 1) {
          this.pageInfo.page--;
        }
        this.$message.success("删除员工成功!");
      } catch (error) {
        this.$message.info("用户取消操作");
      }
    },
    //导出方法
    async exportExcel() {
      // 懒加载使用方法
      // 请求员工所有数据
      let res = await getEmpLists({
        page: 1,
        size: this.pageInfo.total, //数据总数量
      });
      // console.log(res);
      // 取出里面的数据
      let list = res.data.rows;
      // 设置表头数据的语言
      const headers = {
        手机号: "mobile",
        姓名: "username",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };

      let keys = Object.keys(headers);

      let allList = list.map((item) => {
        let arr = [];
        for (const key in headers) {
          let engKey = headers[key];
          if (key == "聘用形式") {
            let str = item[engKey] == 1 ? "正式" : "非正式";
            arr.push(str);
          } else {
            arr.push(item[engKey]);
          }
        }
        return arr;
      });
      console.log(allList);

      // return false;
      // console.log(keys);
      import("@/vendor/Export2Excel").then((excel) => {
        // 这里调用的是vendor/Export2Excel中的方法
        excel.export_json_to_excel({
          header: keys, //表头 必填
          data: allList, //具体数据 必填
          filename: "员工列表", //非必填
          autoWidth: true, //非必填
          bookType: "xlsx", //非必填  各种类型的值
        });
      });
    },
  },
  filters: {
    formatHireType(value) {
      let list = constant.hireType.filter((item) => item.id == value);
      // console.log(list);
      return list[0] ? list[0].value : "非正式";
    },
  },
};
</script>

<style>
.el-link.el-link--primary {
  margin-right: 10px;
}
.el-pagination {
  float: right;
  margin: 10px 20px 20px 0;
}
</style>